package com.summer.util;


import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.summer.common.Const;
import com.summer.common.ServerResponse;

@Component
public class SendEmailUtil {

	public static ServerResponse<String> sentMail(String to, String title, String content) {
		if (empty(to) || empty(title) || empty(content))
			return ServerResponse.createByErrorMessage("发送失败！");
		try {
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			Properties props = System.getProperties();
			props.setProperty("mail.smtp.host", Const.SMTP_SERVER);
			props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.setProperty("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");

			Session session = Session.getInstance(props, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(Const.EMAIL_ACCOUNT, Const.EMAIL_PASSWORD);
				}
			});
			session.setDebug(true);
			Message msg = new MimeMessage(session);

			String nick = javax.mail.internet.MimeUtility.encodeText("大白鼠");
			msg.setFrom(new InternetAddress(nick + "<" + "1278059178@qq.com" + ">"));
			// 设置收件人
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
			// 设置主题
			msg.setSubject(title);
			msg.setContent(content, "text/html;charset=UTF-8");
			msg.setSentDate(new Date());
			Transport transport = session.getTransport("smtp");
			// smtp连接邮件服务器
			transport.connect(Const.SMTP_SERVER, Const.EMAIL_ACCOUNT, Const.EMAIL_PASSWORD);
			// 发送
			transport.sendMessage(msg, msg.getAllRecipients());
			// Transport.send(msg);
			transport.close();
		} catch (MessagingException | UnsupportedEncodingException m) {
			return ServerResponse.createByErrorMessage("发送邮件失败！");
		}

		return ServerResponse.createBySuccessMessage("发送成功，请登录邮箱完成验证！");

	}

	private static boolean empty(String s) {
		if (s == null || s.trim().equals(""))
			return true;
		return false;
	}
}
